from datetime import datetime

from sqlalchemy import Column

from apps.db import BaseModel, Integer, String


class Counter(BaseModel):
    """计数器"""
    __tablename__ = 'tb_count'
    year = Column(String, comment='年份')
    count = Column(Integer, comment='当前的数字')

    @classmethod
    def get_count(cls):
        year = datetime.now().strftime('%Y')
        counter = Counter.filter_by(year=year).first()
        if counter is None:
            counter = Counter()
            counter.year = year
            counter.count = 1
            counter.save(commit=True)
        c = counter.count
        counter.count += 1
        counter.save(commit=True)
        return str(year) + '{:0>4d}'.format(c)
